package com.base.dataStructure.queue;

import com.sun.glass.ui.View;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.Cacheable;

import java.util.Collection;
import java.util.Iterator;

/**
 * @Author: hdhao
 * @Create: 2023/3/31 - 20:32
 * @Version: v1.0
 */
//使用单项环形带哨兵链表实现队列
public class LinkedListQueue<E> implements Queue<E>, Iterable<E> {
    private Node<E> head = new Node<>(null, null);
    private Node<E> tail = head;
    private int size;//节点数
    private int capacity = Integer.MAX_VALUE;//容量

    {
        tail.next = head;
    }
    public LinkedListQueue() {

    }
    public LinkedListQueue(int capacity) {
        this.capacity = capacity;
    }

    //节点类
    private static class Node<E> {
        E value;
        Node<E> next;

        public Node(E value, Node<E> next) {
            this.value = value;
            this.next = next;
        }
    }

    @Override
    public boolean offer(E value) {
        if (isFull()){
            return false;
        }
        Node<E> added = new Node<>(value, head);
        tail.next = added;
        tail = added;
        size++;
        return true;
    }

    /**
     * 返回头结点的值,并删除头结点
     *
     * @return
     */
    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }
        Node<E> first = head.next;
        head.next = first.next;
        size--;
        //当队列中只有一个元素的时候,特殊处理,此时的fist=tail,需要将tail移动回head
        if (first == tail){
            tail = head;
        }
        return first.value;

    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        } else {
            return head.next.value;
        }
    }

    @Override
    public boolean isEmpty() {
        return head == tail;
    }

    @Override
    public boolean isFull() {
        return size == capacity;
    }

    @Override
    public Iterator<E> iterator() {

        return new Iterator<E>() {
            Node<E> p = head.next;

            @Override
            public boolean hasNext() {
                return p != head;
            }

            @Override
            public E next() {
                E value = p.value;
                p = p.next;
                return value;
            }
        };
    }
}
